/*
 * @Author: your name
 * @Date: 2021-06-21 10:05:36
 * @LastEditTime: 2022-08-04 17:52:29
 * @LastEditors: huangbc
 * @Description: In User Settings Edit
 * @FilePath: /shb-pc-fe/src/directive/loadmore.js
 */
/**
 * 当滚动到离底部一定距离时，触发回调.
 * 可用于无限滚动
 * @author dongls 
 */
/* utils */
import { isSafeNumber } from 'pub-bbx-utils'
import Log from '@src/util/log.ts'
import {isAsyncFunction, isFunction} from '@src/util/type'
import { debounce } from 'lodash'

const scrollHandler = debounce(function (event) {
  let option = this._loadmore_option
  let optionTheLoadmoreOptions = option?.loadmoreOptions || {}
  
  if (option.disabled || optionTheLoadmoreOptions.disabled) {
    return Log.warn('loadmore directive option or option?.loadmoreOptions the disabled is true', scrollHandler.name)
  }
  
  let distance = optionTheLoadmoreOptions.distance || option.distance
  let callback = optionTheLoadmoreOptions.callback || option.callback
  
  let target = event.target
  // 暂未处理滚动的方向性
  let MaxScrollHeight = target.scrollHeight - target.offsetHeight
  
  // 未达到触发距离
  if(MaxScrollHeight - target.scrollTop >= distance) {
    return Log.warn('未达到触发距离', scrollHandler.name)
  }
  
  if (!isFunction(callback) && !isAsyncFunction(callback)) {
    return Log.warn('scrollHandler callback is not a function', scrollHandler.name)
  }

  callback(event)
}, 100);

const directive = {
  bind(el, binding, vnode){
    let option = binding.value || {};
    
    // 处理触发loadmore的距离
    if(!isSafeNumber(option.distance)) option.distance = 300;
    
    el._loadmore_option = option;
    el.addEventListener('scroll', scrollHandler, {passive: true})
  },
  unbind(el){
    el && el.removeEventListener('scroll', scrollHandler)
  }
};

export default directive;
